package core

type FilterChan struct {
	Head IFilter

	Tail IFilter
}

type IFilter interface {
	setNext(n IFilter)
	setFront(front IFilter)
	GetNext() IFilter
	GetFront() IFilter
	SessionCreate(session *Session, serverEngin *ServerEngin)
	//收到消息
	MessageRecieved(session *Session, obj interface{}, serverEngin *ServerEngin)
	//客户端断开连接
	SessionClosed(session *Session, serverEngin *ServerEngin)
	//读空闲
	ReadTimeIdle(session *Session)
	//写
	MessageWrite(session *Session, obj interface{}, serverEngin *ServerEngin)
	//写空闲
	WriteTimeIdle(session *Session)
}

func (fchan *FilterChan) AddFilter(f IFilter) {
	//队列为空
	if fchan.Head == nil {
		fchan.Head = f
		fchan.Tail = f
		return
	}
	fchan.Tail.setNext(f)
	f.setFront(fchan.Tail)
	fchan.Tail = f
}

//责任链
type Filter struct {
	//下一个指向
	next IFilter
	//上一个指向
	front IFilter
}

func (f *Filter) setNext(n IFilter) {
	f.next = n
}

func (f *Filter) setFront(front IFilter) {
	f.front = front
}

//获得下一个责任链
func (f *Filter) GetNext() IFilter {
	nP := f.next
	if nP == nil {
		return nil
	}
	return nP
}

//获得上一个责任链
func (f *Filter) GetFront() IFilter {
	fP := f.front
	if fP == nil {
		return nil
	}
	return fP
}

//session创建
func (f *Filter) SessionCreate(session *Session, serverEngin *ServerEngin) {
	n := f.GetNext()
	if n == nil {
		return
	}
	n.SessionCreate(session, serverEngin)
}

//收到消息
func (f *Filter) MessageRecieved(session *Session, obj interface{}, serverEngin *ServerEngin) {
	n := f.GetNext()
	if n == nil {
		return
	}
	n.MessageRecieved(session, obj, serverEngin)
}

//客户端断开连接
func (f *Filter) SessionClosed(session *Session, serverEngin *ServerEngin) {
	n := f.GetNext()
	if n == nil {
		return
	}
	n.SessionClosed(session, serverEngin)
}

//读空闲
func (f *Filter) ReadTimeIdle(session *Session) {
	n := f.GetNext()
	if n == nil {
		return
	}
	n.ReadTimeIdle(session)
}

//写
func (f *Filter) MessageWrite(session *Session, obj interface{}, serverEngin *ServerEngin) {
	n := f.GetFront()
	if n == nil {
		return
	}
	n.MessageWrite(session, obj, serverEngin)
}

//写空闲
func (f *Filter) WriteTimeIdle(session *Session) {
	n := f.GetNext()
	if n == nil {
		return
	}
	n.WriteTimeIdle(session)
}
